﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Solitaire {
    class InputControl {

        Game1 game;
        Table table;
        MouseState ms;

        public InputControl(Game1 game, Table t) {
            this.game = game;
        }

        public void Update(GameTime gameTime) {
            // Allows the game to exit
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                game.Exit();

            UpdateMouse(Mouse.GetState());
        }

        public Card cardUnderMouse(List<Card> cards, KlondikeSlot mouse) {
            Rectangle tmpRect;

            //if (mouse.Count() == 0)
                tmpRect = new Rectangle(ms.X, ms.Y, 1, 1);
            //else
                //tmpRect = new Rectangle(ms.X, ms.Y, Card.width, Card.height);

            List<Card> inter = new List<Card>(); //collection of cards intersecting mouse "rectangle"

            foreach (Card c in cards) {
                if (c.rect.Intersects(tmpRect))
                    inter.Add(c);
            }

            if (inter == null) {
                return null;
            } else {
                inter.Sort(Card.CompareByDepth); //sort by depth
                return inter.ElementAt(inter.Count - 1); //return the "largest" depth found
            }
        }

        public Slot slotUnderMouse(List<Slot> all) {
            Rectangle tmpRect = new Rectangle(ms.X,ms.Y,1,1);

            foreach(Slot s in all) {
                if(s.Rect.Intersects(tmpRect))
                    return s;
            }
            return null;
        }

        public void UpdateMouse(MouseState curr) {
            ms = curr;

            if (ms.LeftButton == ButtonState.Pressed)
                table.MouseClicked(this);
        }

    }
}
